#include "ClientMessageHandler.h"
#include "Controller.h"

#include <iostream>

using namespace resip;
using namespace std;

ClientMessageHandler::ClientMessageHandler(Controller* parent) : m_done(false), m_owner(parent)
{
	initialize();
}

ClientMessageHandler::~ClientMessageHandler()
{
	cleanup();
}

void ClientMessageHandler::initialize()
{
}

void ClientMessageHandler::cleanup()
{
}

// Callbacks: ClientPagerMessageHandle

void ClientMessageHandler::onSuccess(ClientPagerMessageHandle h, const SipMessage & status)
{
	const HeaderFieldValueList* to = status.getRawHeader(Headers::To);
	const HeaderFieldValue* value = to->front();
	string valueString = value->mField;

	string contact = parseContactName(valueString.substr(0, value->mFieldLength));
	m_owner->messageSucceeded(contact);

	cout << ">>CLIENT: Message succesfull: " << contact << endl;
	m_done = true;
}

void ClientMessageHandler::onFailure(ClientPagerMessageHandle h, const SipMessage & status, auto_ptr<Contents> contents)
{
	int statusCode = status.header(h_StatusLine).statusCode();

	if( statusCode == 404 )
		;//m_owner->changeContactStatus(valueString.substr(0, value->mFieldLength), false);

	cout << ">>CLIENT: Message failed" << endl;
	m_done = true;
}

string ClientMessageHandler::parseContactName(string from)
{
	char* buffer = 0;
	char* result = 0;

	buffer = new char[from.size() + 1];
	strcpy(buffer, from.c_str());

	// Filter user

	result = strtok(buffer, ":");
	result = strtok(NULL, "@");

	// Return result

	return string(result);
}